<template>
  <div :style="{ width: '100%', height: '100%' }">
    <div ref="chart" :style="{ width: '100%', height: '100%' }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts/lib/chart/line';
import { hsztmmc } from '@/api/bigscreen/bigscreen';

export default {
  name: 'normalitymmchs',
  data() {
    return {
      chart: null,
      chartData: []
    };
  },
  mounted() {
    this.getData();
    this.tmfive();
    this.initChart();
    window.addEventListener('resize', this.onResize);
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.onResize);
  },
  methods: {
    getData() {
      hsztmmc().then(response => {
        this.chartData = response.data;
      });
    },
    tmfive() {
      setTimeout(() => {
        this.initnormality();
      }, 100);
    },
    initnormality() {
      if (this.chartData.length > 0) {
        this.initChart();
      } else {
        this.tmfive();
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart, "dark");
      const option = {
        title: {
          text: 'MMC RL-Normal P-P ', // 主标题文本
          // subtext: '副标题', // 副标题文本
          left: 'center', // 标题水平位置
          textStyle: {
            fontSize: 14 // 设置标题字体大小为20
          }
        },
        grid: {
          left: '15%',    // 距离左边的距离
          right: '20%',   // 距离右边的距离
          top: '38%',     // 距离顶部的距离
          bottom: '10%',  // 距离底部的距离
          // containLabel: true // 包含坐标轴的标签
        },
        backgroundColor: 'rgba(0, 0, 0, 0)',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['histogram', 'Normal P-P'],
          top: '12%',
          itemWidth: 13,  // 设置图例标记的宽度
          itemHeight: 8, // 设置图例标记的高度
        },
        xAxis: {
          type: 'value',
          // name: '值',
          // splitNumber: 20,
          // min: Math.min(-0.02),
          // max: Math.max(0.3),
          min: Math.min(...this.chartData),
          max: Math.max(...this.chartData),
          splitLine: {
            show: false, // 不显示网格线
          },
          axisLabel: {
            fontSize: 8 // 修改为需要的字体大小
          },
        },
        yAxis: [
          {
            type: 'value',
            name: 'frequency',
            splitNumber: 10, // 设置分割数
            position: 'left',
            alignTicks: true,
            axisLabel: {
              formatter: '{value}',
              fontSize: 8 // 修改为需要的字体大小
            },
            splitLine: {
              show: false // 不显示网格线
            }
          },
          {
            type: 'value',
            name: 'Probability density',
            splitNumber: 10, // 设置分割数
            position: 'right',
            alignTicks: true,
            offset: 20,
            axisLabel: {
              formatter: '{value}',
              fontSize: 8 // 修改为需要的字体大小
            },
            splitLine: {
              show: false // 不显示网格线
            }
          }
        ],
        series: [
          {
            name: 'histogram',
            type: 'bar',
            yAxisIndex: 0,
            data: this.histogramData(),
            barWidth: '60%'
          },
          {
            name: 'Normal P-P',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            data: this.normalDistributionData()
          }
        ]
      }

      this.chart.setOption(option)
    },
    histogramData() {
      const bins = Array.from({ length: 13 }, (_, i) => Math.min(...this.chartData) + (i / 12) * (Math.max(...this.chartData) - Math.min(...this.chartData)))
      const counts = this.chartData.reduce((acc, value) => {
        const index = bins.findIndex(bin => value <= bin)
        if (index >= 0) {
          acc[index] += 1
        } else {
          acc[bins.length - 1] += 1
        }
        return acc
      }, new Array(13).fill(0))

      return bins.map((bin, i) => ({
        name: `[${bins[i].toFixed(2)}, ${bins[i + 1] ? bins[i + 1].toFixed(2) : bins[i].toFixed(2) + 0.01}]`,
        value: [bin, counts[i] / this.chartData.length]
      }))
    },
    normalDistributionData() {
      const mean = this.chartData.reduce((sum, value) => sum + value, 0) / this.chartData.length
      const stdDev = Math.sqrt(this.chartData.reduce((sum, value) => sum + (value - mean) ** 2, 0) / this.chartData.length)

      const xValues = []
      const yValues = []

      for (let i = 0; i < 100; i++) {
        const x = Math.min(...this.chartData) + (Math.max(...this.chartData) - Math.min(...this.chartData)) * i / 99
        xValues.push(x)

        const y = (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(-0.5 * ((x - mean) / stdDev) ** 2)
        yValues.push(y)
      }

      return xValues.map((x, i) => [x, yValues[i]])
    },
    onResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  }
}
</script>
